package com.example.module_hp_white_noise.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.library.baseAdapters.BR;
import androidx.lifecycle.Observer;

import android.content.ClipData;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;

import com.example.module_hp_white_noise.R;
import com.example.module_hp_white_noise.base.BaseMvvmActivity;
import com.example.module_hp_white_noise.base.BaseUtils;
import com.example.module_hp_white_noise.databinding.ActivityHpSleepFocusBinding;
import com.example.module_hp_white_noise.entity.Music;
import com.example.module_hp_white_noise.service.MusicService;
import com.example.module_hp_white_noise.util.Utils;
import com.example.module_hp_white_noise.view.PickerScrollView;
import com.example.module_hp_white_noise.util.SleepUtils;
import com.example.module_hp_white_noise.viewModel.SleepFocusViewModel;
import com.fwlst.lib_base.utils.AdUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
@Route(path = "/hpWhiteNoise/route/HpSleepFocusActivity")
public class HpSleepFocusActivity extends BaseMvvmActivity<ActivityHpSleepFocusBinding, SleepFocusViewModel> {
    private int[] times={1,3,5,10,15,20,25,30,35,40,45,50,55,60,70,80,90,100,110,120};
    private int[] indexArr={0,2,97,120,128};//音频资源下标
    private int selectTime;//滑动选中时间
    private int countdownTime;//倒计时剩余时间，单位s
    private CountDownTimer counter;//计时器
    private MusicService.MusicServiceBinder serviceBinder;
    private Music music;
    private List<Music> musicList;
    @Override
    protected int initLayout() {
        return R.layout.activity_hp_sleep_focus;
    }

    @Override
    protected int initBR() {
        return BR.data;
    }

    @Override
    protected void initView() {
        BaseUtils.setStatusBar(this,0xff1E2746);
        //banner广告
        AdUtils.INSTANCE.loadBannerAd(this,binding.bannerContainer);
        //返回按钮
        binding.returnTb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //监听按钮点击
        viewModel.getCurrentType().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if(integer==0) return;
                if(!BaseUtils.isNetworkConnected(mContext)){
                    Toast.makeText(mContext, "网络连接异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                switch (integer){
                    case 1://点击了结束
                        counter.cancel();
                        countdownTime=selectTime*60;
                        serviceBinder.seekTo(0);
                        if(serviceBinder.isPlaying()){
                            serviceBinder.playOrPause();
                        }
                        break;
                    case 2://点击了开始
                        if(musicList==null){
                            initMusicList();
                        }else {
                            serviceBinder.playOrPause();
                        }
                        startTimer();
                        break;
                    case 3://点击了暂停
                        counter.cancel();
                        serviceBinder.playOrPause();
                        break;
                }
            }
        });
        initData();
        //滚动监听
        binding.pickerView.setOnSelectListener(new PickerScrollView.onSelectListener() {
            @Override
            public void onSelect(String pickers) {
                selectTime=Integer.parseInt(pickers);
                countdownTime=selectTime*60;
            }
        });
        // 绑定service
        Intent i = new Intent(this, MusicService.class);
        bindService(i, mServiceConnection, BIND_AUTO_CREATE);
        //切换音乐
        binding.sleepFocusCut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BaseUtils.isNetworkConnected(mContext)){
                    Toast.makeText(mContext, "网络连接异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(viewModel.getCurrentType().getValue()==2){
                    serviceBinder.playNext();
                    showToast("切换到 "+serviceBinder.getCurrentMusic().title);
                }else {
                    showToast("请先开始专注");
                }
            }
        });
    }
    // 定义与服务的连接的匿名类
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        // 绑定成功时调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            // 绑定成功后，取得MusicSercice提供的接口
            serviceBinder = (MusicService.MusicServiceBinder) service;
            initMusic();
            // 注册监听器
            serviceBinder.registerOnStateChangeListener(listenr);
            Music item = serviceBinder.getCurrentMusic();
            if(serviceBinder.isPlaying()){
                serviceBinder.playOrPause();
            }
            /*if (serviceBinder.isPlaying()){
                // 如果正在播放音乐, 更新控制栏信息
                btnPlayOrPause.setImageResource(R.drawable.zanting);
                playingTitleView.setText(item.title);
                playingArtistView.setText(item.artist);
                if (item.isOnlineMusic){
                    Glide.with(getApplicationContext())
                            .load(item.imgUrl)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
                else {
                    ContentResolver resolver = getContentResolver();
                    Bitmap img = Utils.getLocalMusicBmp(resolver, item.imgUrl);
                    Glide.with(getApplicationContext())
                            .load(img)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
            }
            else if (item != null){
                // 当前有可播放音乐但没有播放
                btnPlayOrPause.setImageResource(R.drawable.bofang);
                playingTitleView.setText(item.title);
                playingArtistView.setText(item.artist);
                if (item.isOnlineMusic){
                    Glide.with(getApplicationContext())
                            .load(item.imgUrl)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
                else {
                    ContentResolver resolver = getContentResolver();
                    Bitmap img = Utils.getLocalMusicBmp(resolver, item.imgUrl);
                    Glide.with(getApplicationContext())
                            .load(img)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(playingImgView);
                }
            }*/
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 断开连接时注销监听器
            serviceBinder.unregisterOnStateChangeListener(listenr);
        }
    };

    // 实现监听器监听MusicService的变化，
    private MusicService.OnStateChangeListenr listenr = new MusicService.OnStateChangeListenr() {

        @Override
        public void onPlayProgressChange(long played, long duration) {}

        @Override
        public void onPlay(Music item) {
        }

        @Override
        public void onPause() {
            // 播放状态变为暂停时
        }
    };
    //初始化数据
    private void initData(){
        List<String> items = new ArrayList<>();
        for (int timeVal:times) {
            items.add("" +timeVal);
        }
        binding.pickerView.setData(items);
        binding.pickerView.setSelected(7);
        selectTime=times[7];
        countdownTime=selectTime*60;

    }
    //初始化播放器
    private void initMusic(){

        serviceBinder.removeAllMusic();
        serviceBinder.setPlayMode(Utils.TYPE_SINGLE);
    }
    private void initMusicList(){
        musicList= new ArrayList<>();
        String objString = BaseUtils.getJson("baizaoying.json",mContext);
        try {
            JSONArray jsonArray = new JSONArray(objString);
            for (int i=0;i<indexArr.length;i++){
                JSONObject thisObj = jsonArray.getJSONObject(indexArr[i]);
                musicList.add(new Music(
                        Utils.HTTPS_URL+thisObj.getString("ossId"),
                        thisObj.getString("name"),
                        "",
                        "music_img"+(indexArr[i]%Utils.musicImgCount+1),
                        true
                ));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //serviceBinder.addPlayList(music);
        serviceBinder.seekTo(0);
        serviceBinder.addPlayList(musicList);
    }
    //开始计时器
    private void startTimer(){
        if(counter!=null){
            counter.cancel();
        }
        counter = new CountDownTimer(countdownTime*1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                countdownTime--;
                setTimesText();
            }
            @Override
            public void onFinish() {
                viewModel.setCurrentType(1);
                showToast("刚刚专注了"+selectTime+"分钟");
            }
        };
        counter.start();
    }
    //改变计时器
    private void setTimesText(){
        binding.sleepFocusTimeText.setText(SleepUtils.timeParse(countdownTime*1000));
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(counter!=null){
            counter.cancel();
        }
        if(serviceBinder.isPlaying()){
            serviceBinder.playOrPause();
        }
        serviceBinder.removeAllMusic();
        unbindService(mServiceConnection);
        AdUtils.INSTANCE.destroyBannerAd();
    }
}